<template>
  <div class="key-management">
    <div class="page-card">
      <div style="margin-left: 20px;font-weight: bold;color: rgb(66,66,100);">
        密钥管理
      </div>
      <el-divider />
      
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <!-- 筛选标题和搜索 -->
        <div class="filter-header">
          <div>
            <h3 class="filter-title">应用密钥</h3>
          </div>
          <div class="search-section-right">
            <el-input
              v-model="searchQuery"
              placeholder="搜索应用名称或密钥"
              @input="handleSearch"
              clearable
              class="search-input-el"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
        
        <!-- 筛选条件 -->
        <div>
          <!-- 状态筛选 -->
          <div class="filter-group">
            <div class="filter-row">
              <div class="filter-label">状态</div>
              <div class="filter-options">
                <button 
                  v-for="status in statusOptions" 
                  :key="status.value"
                  :class="['filter-option', { active: activeStatus === status.value }]"
                  @click="filterByStatus(status.value)"
                >
                  {{ status.label }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载密钥列表...</p>
      </div>

      <!-- 密钥卡片网格 -->
      <div v-else class="keys-grid">
        <div 
          v-for="app in filteredApps" 
          :key="app.appId"
          class="key-card"
        >
          <!-- 卡片头部：图标 + 标题 + 状态 -->
          <div class="card-header">
            <!-- 左侧图标 -->
            <div class="app-icon">
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                <circle cx="9" cy="9" r="2"></circle>
                <path d="M21 15.5c-1.5-1.5-4-1.5-5.5 0"></path>
                <path d="M14 21.5c-1.5-1.5-4-1.5-5.5 0"></path>
              </svg>
            </div>
            
            <!-- 右侧内容区 -->
            <div class="header-content">
              <!-- 标题行 -->
              <div class="title-row">
                <h3 class="app-name">{{ app.appName || '未知应用' }}</h3>
                <div class="status-area">
                  <span v-if="app.appStatus === '0'" class="status-badge status-active">运行中</span>
                  <span v-else class="status-badge status-inactive">已停止</span>
                </div>
              </div>
              
              <!-- 应用信息行 -->
              <div class="info-row">
                <span class="app-type">{{ app.appType || '未知类型' }}</span>
                <span class="app-user">{{ app.appUser || '未知用户' }}</span>
              </div>
            </div>
          </div>
          
          <!-- 密钥信息区域 -->
          <div class="card-content">
            <div class="key-info">
              <div class="key-item">
                <span class="key-label">API Key:</span>
                <div class="key-value-container">
                  <span class="key-value">{{ maskKey(app.apiKey) }}</span>
                  <button class="btn-copy" @click="copyToClipboard(app.apiKey)" title="复制">
                    <el-icon><DocumentCopy /></el-icon>
                  </button>
                </div>
              </div>
              
              <div class="key-item">
                <span class="key-label">Secret Key:</span>
                <div class="key-value-container">
                  <span class="key-value">{{ maskKey(app.secretKey) }}</span>
                  <button class="btn-copy" @click="copyToClipboard(app.secretKey)" title="复制">
                    <el-icon><DocumentCopy /></el-icon>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 元信息 -->
          <div class="card-meta">
            <div class="meta-left">
              <span class="create-time">创建: {{ formatDate(app.createTime) }}</span>
            </div>
            <div class="meta-right">
              <span class="update-time">{{ formatDate(app.updateTime) }}更新</span>
            </div>
          </div>
          
          
          <!-- 分割线 -->
          <div class="divider"></div>
          
          <!-- 操作按钮 -->
          <div class="key-actions">
            <button class="btn-action btn-regenerate" @click="regenerateSecretKey(app)">
              <el-icon class="action-icon">
                <Refresh />
              </el-icon>
              重新生成密钥
            </button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredApps.length === 0" class="empty-state">
        <div class="empty-icon">
          <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
            <line x1="8" y1="21" x2="16" y2="21"></line>
            <line x1="12" y1="17" x2="12" y2="21"></line>
          </svg>
        </div>
        <h3>暂无应用密钥</h3>
        <p>还没有应用密钥信息</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, DocumentCopy, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import appAPI from '@/api/agriculture/xctl/appManage'
import { getToken } from '@/utils/auth.js'

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const activeStatus = ref('all')
const loading = ref(false)
const originalApps = ref([])

// 状态选项
const statusOptions = [
  { value: 'all', label: '全部' },
  { value: '0', label: '运行中' },
  { value: '1', label: '已停止' }
]

// 获取应用列表
const fetchApps = async () => {
  // 检查登录状态
  if (!getToken()) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  try {
    loading.value = true
    const response = await appAPI.getAppList()
    if (response.code === 200) {
      originalApps.value = response.rows || []
    } else {
      ElMessage.error('获取应用列表失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取应用列表出错:', error)
    if (error.message.includes('未授权')) {
      ElMessage.warning('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('获取应用列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 计算属性：过滤后的应用
const filteredApps = computed(() => {
  let filtered = originalApps.value
  
  // 按状态筛选
  if (activeStatus.value !== 'all') {
    filtered = filtered.filter(app => app.appStatus === activeStatus.value)
  }
  
  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(app => 
      app.appName?.toLowerCase().includes(query) ||
      app.appType?.toLowerCase().includes(query) ||
      app.appUser?.toLowerCase().includes(query) ||
      app.apiKey?.toLowerCase().includes(query)
    )
  }
  
  return filtered
})

// 搜索处理
const handleSearch = () => {
  // 计算属性会自动处理过滤，这里不需要额外操作
}

// 按状态筛选
const filterByStatus = (status) => {
  activeStatus.value = status
  handleSearch()
}

// 掩码显示密钥
const maskKey = (key) => {
  if (!key) return '未设置'
  if (key.length <= 8) return key
  return key.substring(0, 4) + '****' + key.substring(key.length - 4)
}

// 复制到剪贴板
const copyToClipboard = async (text) => {
  if (!text) {
    ElMessage.warning('密钥为空，无法复制')
    return
  }
  
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('密钥已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 重新生成密钥
const regenerateSecretKey = async (app) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新生成应用 "${app.appName || '未知应用'}" 的密钥吗？\n\n注意：重新生成后，原密钥将失效，请及时更新相关配置。`,
      '重新生成密钥',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API重新生成密钥
    const response = await appAPI.regenerateAppKey(app.appId)
    
    if (response.code === 200) {
      // 重新获取应用列表以更新密钥信息
      await fetchApps()
      ElMessage.success('密钥重新生成成功')
    } else {
      ElMessage.error('重新生成密钥失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重新生成密钥失败:', error)
      ElMessage.error('重新生成密钥失败，请稍后重试')
    }
  }
}



// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchApps()
})
</script>

<style scoped>
.key-management {
  min-height: 100vh;
  background: #f8fafc;
}

.page-card {
  
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin: 24px;
 
 overflow-y: auto;
   height: 80vh;
}

.search-section {
  padding: 24px;
  margin-bottom: 32px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.search-section-right {
  flex-shrink: 0;
}

.filter-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.filter-label {
  font-size: 12px;
  color: rgb(113,111,141);
  flex-shrink: 0;
}

.filter-options {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  flex: 1;
}

.filter-option {
  padding: 3px 12px;
  border: none;
  background: transparent;
  color: rgb(113,111,141);
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.filter-option:hover {
  background: rgb(238, 236, 251);
  color: rgb(136, 94, 237);
}

.filter-option.active {
  background: rgb(238, 236, 251);
  color: rgb(136, 94, 237);
}

.keys-grid {
  display: grid;
   
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 24px;
  margin-bottom: 48px;
  margin-left: 20px;
  margin-right: 20px;
}

.key-card {
  background: linear-gradient(135deg, rgb(244, 244, 246) 20%,#fff 35%, #fff 100%);
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.key-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  gap: 16px;
}

.app-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.header-content {
  flex: 1;
  min-width: 0;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-area {
  flex-shrink: 0;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background: #f0f9ff;
  color: #0369a1;
}

.status-inactive {
  background: #fef2f2;
  color: #dc2626;
}

.info-row {
  display: flex;
  gap: 12px;
  font-size: 14px;
  color: #6b7280;
}

.app-type,
.app-user {
  background: #f3f4f6;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.card-content {
  padding: 0 20px 16px;
}

.key-info {
  space-y: 12px;
}

.key-item {
  margin-bottom: 12px;
}

.key-label {
  display: block;
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 4px;
  font-weight: 500;
}

.key-value-container {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 8px 12px;
}

.key-value {
  flex: 1;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  color: #374151;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.btn-copy {
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-copy:hover {
  background: #e5e7eb;
  color: #374151;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px 16px;
  font-size: 12px;
  color: #6b7280;
}

.divider {
  height: 1px;
  background: #e5e7eb;
  margin: 0 20px;
}

.key-actions {
  padding: 16px 20px;
  display: flex;
  gap: 12px;
}

.btn-action {
  flex: 1;
  padding: 8px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.btn-action:hover {
  background: #f9fafb;
  border-color: #d1d5db;
}

.btn-regenerate {
  background: #fef3c7;
  color: #d97706;
  border-color: #fbbf24;
}

.btn-regenerate:hover {
  background: #fde68a;
}

.btn-view {
  background: #eff6ff;
  color: #1d4ed8;
  border-color: #bfdbfe;
}

.btn-view:hover {
  background: #dbeafe;
}

.action-icon {
  font-size: 16px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #6b7280;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #6b7280;
}

.empty-icon {
  margin-bottom: 24px;
  opacity: 0.5;
}

.empty-state h3 {
  font-size: 24px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}


</style>